package com.rdk.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rdk.entity.AnalysisBucketBean;
import com.rdk.entity.AnalysisDataBean;
import com.rdk.entity.AnalysisDataForWebsiteBean;
import com.rdk.entity.ChatDataBean;
import com.rdk.entity.DataBean;
import com.rdk.entity.EmotionBean;
import com.rdk.entity.EmotionJsonBean;
import com.rdk.entity.IndexEntity;
import com.rdk.entity.IndexRequest;
import com.rdk.entity.PSKeyWord;
import com.rdk.entity.SearchRequestParam;
import com.rdk.entity.SearchResponseEntity;
import com.rdk.service.PublicSentimentService;
import com.rdk.utils.GsonUtil;
import com.rdk.utils.StringUtil;
import com.rdk.wechat.common.Constant;
import com.rdk.wechat.request.impl.BaseRequest;
import com.rdk.wechat.util.JSONutils;

import net.sf.json.JSONArray;

public class PublicSentimentServiceImpl extends BaseRequest implements PublicSentimentService {

	public PublicSentimentServiceImpl() {
		super(null);
	}

	@Override
	public SearchResponseEntity getpositiveOrNegative(SearchRequestParam searchRequestParam, String key) {
		String jsonParma = JSONutils.ObjectToJson(searchRequestParam);
		System.out.println("request.json==" + jsonParma);
		we.setWebFlag("publicSentimentUrl");
		we.setServiceName(Constant.PublicSentimentServiceName.SEARCH);
		we.setOpName(Constant.PublicSentimentOpName.POSITIVEORNEGATIVE);
		String url = this.getUrl(we);
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		httppost.addHeader("usergid", key);
		StringEntity myEntity = new StringEntity(jsonParma, ContentType.APPLICATION_JSON);// 鐠佸墽鐤嗛崗铚傜秼鐠囬攱鐪伴悽銊ф暏缁鐎�
																							// 閻拷
		SearchResponseEntity sarchResponseEntity = new SearchResponseEntity();															// json閵嗭拷
		httppost.setEntity(myEntity);// 鐠佸墽鐤嗙拠閿嬬湴娴ｏ拷
		try {
			HttpResponse response = httpclient.execute(httppost);
			int stateCode = response.getStatusLine().getStatusCode();
			if (stateCode == 200) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
 					Gson gson = new Gson();
					String jsonStr = EntityUtils.toString(entity,"UTF-8");
					System.out.println(jsonStr);
					sarchResponseEntity = gson.fromJson(jsonStr, SearchResponseEntity.class);
					System.out.println(sarchResponseEntity);
				}
			}
		} catch (Exception e) {
			System.out.println("------------" + e);
		}
		
	
		
		return sarchResponseEntity;
	}
	
	public static void main(String[] args) {
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.rdk.service.PublicSentimentService#getsearchkws(com.rdk.entity.
	 * SearchRequestParam, java.lang.String)
	 */
	public SearchResponseEntity getsearchkws(SearchRequestParam searchRequestParam, String key) {
		String jsonParma = JSONutils.ObjectToJson(searchRequestParam);
		System.out.println("request.json==" + jsonParma);
		we.setWebFlag("publicSentimentUrl");
		we.setServiceName(Constant.PublicSentimentServiceName.SEARCH);
		we.setOpName(Constant.PublicSentimentOpName.SEARCHKWS);
		String url = this.getUrl(we);
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		httppost.addHeader("usergid", key);
		StringEntity myEntity = new StringEntity(jsonParma, ContentType.APPLICATION_JSON);// 鐠佸墽鐤嗛崗铚傜秼鐠囬攱鐪伴悽銊ф暏缁鐎�
																							// 閻拷
																							// json閵嗭拷
		SearchResponseEntity sarchResponseEntity = new SearchResponseEntity();
		httppost.setEntity(myEntity);// 鐠佸墽鐤嗙拠閿嬬湴娴ｏ拷
		String jsonStr = null;
		try {
			HttpResponse response = httpclient.execute(httppost);
			int stateCode = response.getStatusLine().getStatusCode();
			if (stateCode == 200) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					Gson gson = new Gson();
					sarchResponseEntity = gson.fromJson(EntityUtils.toString(entity,"UTF-8"), SearchResponseEntity.class);
					System.out.println("------------" + jsonStr);
				}
			}
		} catch (Exception e) {
			System.out.println("------------" + e);
		}
		return sarchResponseEntity;
	}

	@Override
	public SearchResponseEntity getPSList(SearchRequestParam searchRequestParam, String key) {
		String jsonParma = JSONutils.ObjectToJson(searchRequestParam);
		System.out.println("request.json==" + jsonParma);
		we.setWebFlag("publicSentimentUrl");
		we.setServiceName(Constant.PublicSentimentServiceName.SEARCH);
		we.setOpName(Constant.PublicSentimentOpName.OPINIONVALUE);
		String url = this.getUrl(we);
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		httppost.addHeader("usergid", key);
		StringEntity myEntity = new StringEntity(jsonParma, ContentType.APPLICATION_JSON);// 鐠佸墽鐤嗛崗铚傜秼鐠囬攱鐪伴悽銊ф暏缁鐎�
																							// 閻拷
																							// json閵嗭拷
		SearchResponseEntity sarchResponseEntity = new SearchResponseEntity();
		httppost.setEntity(myEntity);// 鐠佸墽鐤嗙拠閿嬬湴娴ｏ拷
		try {
			HttpResponse response = httpclient.execute(httppost);
			int stateCode = response.getStatusLine().getStatusCode();
			if (stateCode == 200) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					Gson gson = new Gson();
					sarchResponseEntity = gson.fromJson(EntityUtils.toString(entity,"UTF-8"), SearchResponseEntity.class);
					System.out.println("------------" + sarchResponseEntity.toString());
				}
			}
		} catch (Exception e) {
			System.out.println("------------" + e);
		}
		return sarchResponseEntity;
	}

	public SearchResponseEntity getOpinionvaluebyid(SearchRequestParam searchRequestParam, String key) {
		String jsonParma = JSONutils.ObjectToJson(searchRequestParam);
		System.out.println("request.json==" + jsonParma);
		we.setWebFlag("publicSentimentUrl");
		we.setServiceName(Constant.PublicSentimentServiceName.SEARCH);
		we.setOpName(Constant.PublicSentimentOpName.OPINIONVALUEBYID);
		String url = this.getUrl(we);
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);
		httppost.addHeader("usergid", key);
		StringEntity myEntity = new StringEntity(jsonParma, ContentType.APPLICATION_JSON);// 璁剧疆鍏蜂綋璇锋眰鐢ㄧ敤绫诲瀷
																							// 鐢�
																							// json銆�
		SearchResponseEntity sarchResponseEntity = new SearchResponseEntity();
		httppost.setEntity(myEntity);// 璁剧疆璇锋眰浣�
		
		try {
			HttpResponse response = httpclient.execute(httppost);
			int stateCode = response.getStatusLine().getStatusCode();
			if (stateCode == 200) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					Gson gson = new Gson();
					sarchResponseEntity = gson.fromJson(EntityUtils.toString(entity,"UTF-8"), SearchResponseEntity.class);
					System.out.println("------------" + sarchResponseEntity.toString());
				}
			}
		} catch (Exception e) {
			System.out.println("------------" + e);
		}
		return sarchResponseEntity;
	}

	/**
	 * @Title: getIndexInfo @Description: 获取整个首页数据 @param @param indexRequest
	 *         （用户，凭证key，今天开始时间，结束时间） @param @return 设定文件 @return IndexEntity
	 *         返回类型 @throws
	 */
	public IndexEntity getIndexInfo(IndexRequest indexRequest) {
		SearchRequestParam kp = new SearchRequestParam();
		kp.setCurrentPage(indexRequest.getCurrentPage());
		kp.setLimit(indexRequest.getLimit());
		/*kp.setStartTime(indexRequest.getStartTime());
		kp.setEndTime(indexRequest.getEndTime());*/
		kp.setTimeout(1000);
		kp.setType(0);
		kp.setUserAgentNo(indexRequest.getUserAgentNo());
		
		IndexEntity indexEntity = new IndexEntity();
		//JSONArray jArray = null;
		// 鑾峰彇姝ｈ礋闈俊鎭�
		/*SearchResponseEntity searchResponseEntity = this.getpositiveOrNegative(kp, indexRequest.getKey());
		if (searchResponseEntity.getData() != null) {
			jArray = JSONArray.fromObject(searchResponseEntity.getData());
			List<AnalysisDataBean> analyList = (List<AnalysisDataBean>) JSONArray.toCollection(jArray,
					AnalysisDataBean.class);
			List<AnalysisDataBean> analyList = GsonUtil.jsonToList(searchResponseEntity.getData().toString(), new TypeToken<List<AnalysisDataBean>>(){}.getType());
			for (AnalysisDataBean asdb : analyList) {
				int k = Integer.parseInt(asdb.getKey());
				switch (k) {
				case 0:
					indexEntity.setNormalNum(asdb.getDoc_count() - asdb.getSubAggsField().getSum_other_doc_count());
					break;
				case 1:
					indexEntity.setPositiveNum(asdb.getDoc_count() - asdb.getSubAggsField().getSum_other_doc_count());
					break;
				case 2:
					indexEntity.setNegativeNum(asdb.getDoc_count() - asdb.getSubAggsField().getSum_other_doc_count());
					break;
				}
			}
			indexEntity.setTotalNum(indexEntity.getPositiveNum() + indexEntity.getNegativeNum());
		}*/
		SearchResponseEntity searchResponseEntity = this.getPSList(kp, indexRequest.getKey());
		// 鑾峰彇鍒楄〃
		if (searchResponseEntity.getData() != null) {
			List<AnalysisDataForWebsiteBean> adwList = GsonUtil.jsonToList(searchResponseEntity.getData().toString(), new TypeToken<List<AnalysisDataForWebsiteBean>>(){}.getType());
			List<DataBean> dataList = new ArrayList<DataBean>();
			for(AnalysisDataForWebsiteBean adw : adwList){
				DataBean bean = adw.getData().get(0);
				String titleStr = bean.getContent();
				if (StringUtil.isEmpty(bean.getTitle())) {
					
					bean.setTitle(titleStr.length() > 10 ? (titleStr.substring(0, 10) + "...")
							: (titleStr.substring(0, titleStr.length())));
				}
				bean.setContent("");
				bean.setDoc_count(adw.getDoc_count());
				
				dataList.add(bean);
			}
			
			indexEntity.setDataBeanList(dataList);
		}

		return indexEntity;
	}

	/**
	 * @Title: searchkws @Description: 首页搜索 @param IndexRequest indexRequest
	 *         （用户，凭证key，搜索关键字） @param @return 设定文件 @return IndexEntity
	 *         返回类型 @throws
	 */
	public List<DataBean> searchkws(IndexRequest indexRequest) {
		SearchRequestParam kp = new SearchRequestParam();
		kp.setCurrentPage(indexRequest.getCurrentPage());
		kp.setLimit(indexRequest.getLimit());
		kp.setTimeout(1000);
		kp.setType(0);
		kp.setUserAgentNo(indexRequest.getUserAgentNo());
		kp.setSearchkws(indexRequest.getKeyWord());
		SearchResponseEntity searchResponseEntity = this.getsearchkws(kp, indexRequest.getKey());
		// 鑾峰彇鍒楄〃
		List<DataBean> dataList = null;
		if (searchResponseEntity.getData() != null) {
			
			List<AnalysisDataForWebsiteBean> adwList = GsonUtil.jsonToList(searchResponseEntity.getData().toString(), new TypeToken<List<AnalysisDataForWebsiteBean>>(){}.getType());
			dataList = new ArrayList<DataBean>();
			for(AnalysisDataForWebsiteBean adw : adwList){
				if (null != adw){
					DataBean bean = adw.getData().get(0);
					String titleStr = bean.getContent();
					if (StringUtil.isEmpty(bean.getTitle())) {
						bean.setTitle(titleStr.length() > 10 ? (titleStr.substring(0, 10) + "...")
								: (titleStr.substring(0, titleStr.length())));
					}
					/*bean.setContent("");*/
					bean.setDoc_count(adw.getDoc_count());
					dataList.add(bean);
				}
			}
		}
		
		return dataList;
	}

	/**
	 * @Title: searchkws @Description: 图表 @param IndexRequest
	 *         indexRequest（用户，凭证key，开始时间，结束时间） @param @return 设定文件 @return
	 *         IndexEntity 返回类型 @throws
	 */
	public ChatDataBean searchChat(IndexRequest indexRequest) {
		SearchRequestParam kp = new SearchRequestParam();
		kp.setStartTime(indexRequest.getStartTime());
		kp.setEndTime(indexRequest.getEndTime());
		kp.setUserAgentNo(indexRequest.getUserAgentNo());
		kp.setTimeout(1000);
		kp.setType(0);
		ChatDataBean cdb = new ChatDataBean(indexRequest.getStartTime(), indexRequest.getEndTime());
		// 鑾峰彇姝ｈ礋闈俊鎭�
		SearchResponseEntity searchResponseEntity = this.getpositiveOrNegative(kp, indexRequest.getKey());
		/*JsonArray jArray = searchResponseEntity.getData();
		String jsonStr = "{\"data\":" + jArray + "}";
		ObjectMapper objMapper = new ObjectMapper();
		objMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);*/
		String jsonStr = searchResponseEntity.getData().toString();
		System.out.println("char response:-------------------" + jsonStr);
		List<EmotionJsonBean> list = GsonUtil.jsonToList(jsonStr,new TypeToken<List<EmotionJsonBean>>(){}.getType());
		System.out.println("---EmotionJsonBean--:"+list);
		EmotionJsonBean json =new EmotionJsonBean();
		if(list!=null&&list.size()>0){
			json = list.get(0);
		}
		/*PositiveOrNegativeBean jsonList = objMapper.readValue(jsonStr, PositiveOrNegativeBean.class);*/
		int maxTotal = 0 ;
		
		for (AnalysisDataBean analysd : json.getPnResult()) {
			if (analysd != null) {
				if ("0".equals(analysd.getKey())) {
					for (AnalysisBucketBean analybb : analysd.getSubAggsField().getBuckets()) {
						if (cdb.getNormalNumMap().containsKey(analybb.getKey())) {
							cdb.getNormalNumMap().put(analybb.getKey(), analybb.getDoc_count());
							cdb.getTotalNumMap().put(analybb.getKey(), cdb.getTotalNumMap().get(analybb.getKey()) + analybb.getDoc_count());
							if(maxTotal < cdb.getTotalNumMap().get(analybb.getKey())){
								maxTotal  = cdb.getTotalNumMap().get(analybb.getKey());
							}
						}
					}
				} else if ("1".equals(analysd.getKey())) {
					for (AnalysisBucketBean analybb : analysd.getSubAggsField().getBuckets()) {
						if (cdb.getNegativeNumMap().containsKey(analybb.getKey())) {
							cdb.getNegativeNumMap().put(analybb.getKey(), analybb.getDoc_count());
							cdb.getTotalNumMap().put(analybb.getKey(),
									cdb.getTotalNumMap().get(analybb.getKey()) + analybb.getDoc_count());
							if(maxTotal < cdb.getTotalNumMap().get(analybb.getKey())){
								maxTotal  = cdb.getTotalNumMap().get(analybb.getKey());
							}
						}
					}
				} else if ("2".equals(analysd.getKey())) {
					for (AnalysisBucketBean analybb : analysd.getSubAggsField().getBuckets()) {
						if (cdb.getPositiveNumMap().containsKey(analybb.getKey())) {
							cdb.getPositiveNumMap().put(analybb.getKey(), analybb.getDoc_count());
							cdb.getTotalNumMap().put(analybb.getKey(),
									cdb.getTotalNumMap().get(analybb.getKey()) + analybb.getDoc_count());
							if(maxTotal < cdb.getTotalNumMap().get(analybb.getKey())){
								maxTotal  = cdb.getTotalNumMap().get(analybb.getKey());
							}
						}
					}
				}
			}
		}
		
		for (EmotionBean em : json.getMoodResult()) {
			if (cdb.getNormalNumMap().containsKey(em.getKey())){
				cdb.getEmotionTmepMap().put(em.getKey(), em.getSubAggsAvg().getValue());
			}
		}
		cdb.setNegativeNumMap(cdb.sortMapByKey(cdb.getNegativeNumMap()));
		cdb.setPositiveNumMap(cdb.sortMapByKey(cdb.getPositiveNumMap()));
		cdb.setTotalNumMap(cdb.sortMapByKey(cdb.getTotalNumMap())); 
		cdb.setNormalNumMap(cdb.sortMapByKey(cdb.getNormalNumMap()));
		cdb.setEmotionNumMap(cdb.sortMapByKey(cdb.haldEmotion(cdb.getEmotionTmepMap(), maxTotal)));

		return cdb;
	}

	/**
	 * @Title: getPSListByCon @Description: 获取舆情列表 @param IndexRequest
	 *         indexRequest（用户，凭证key，开始时间，结束时间） @param @return 设定文件 @return
	 *         IndexEntity 返回类型 @throws
	 */
	@SuppressWarnings("unchecked")
	public List<DataBean> getPSListByCon(IndexRequest indexRequest) {
		SearchRequestParam kp = new SearchRequestParam();
		kp.setCurrentPage(indexRequest.getCurrentPage());
		kp.setLimit(indexRequest.getLimit());
		kp.setTimeout(1000);
		kp.setType(0);
		kp.setUserAgentNo(indexRequest.getUserAgentNo());
		kp.setSearchkws(indexRequest.getKeyWord());
		SearchResponseEntity searchResponseEntity = this.getPSList(kp, indexRequest.getKey());
		List<DataBean> dataList = null;
		// 获取列表
		if (searchResponseEntity.getData() != null) {
			JSONArray jArray = JSONArray.fromObject(searchResponseEntity.getData());
			dataList = (List<DataBean>) JSONArray.toCollection(jArray, DataBean.class);
			for (DataBean bean : dataList) {
				String titleStr = bean.getContent();
				if (StringUtil.isEmpty(bean.getTitle())) {
					bean.setTitle(titleStr.length() > 10 ? (titleStr.substring(0, 10) + "...")
							: (titleStr.substring(0, titleStr.length())));
				}
				/*bean.setContent("");*/
			}
		}
		return dataList;
	}

	/**
	 * @Title: getPSById @Description: 根据id获取单条舆情 @param IndexRequest
	 *         indexRequest（用户，凭证key，舆情id） @param @return 设定文件 @return
	 *         IndexEntity 返回类型 @throws
	 */
	public List<DataBean> getPSById(IndexRequest indexRequest) {
		SearchRequestParam kp = new SearchRequestParam();
		kp.setCurrentPage(indexRequest.getCurrentPage());
		kp.setLimit(indexRequest.getLimit());
		kp.setTimeout(1000);
		kp.setType(0);
		kp.setUserAgentNo(indexRequest.getUserAgentNo());
		kp.setSearchkws(indexRequest.getKeyWord());
		kp.setId(indexRequest.getPsId());
		SearchResponseEntity searchResponseEntity = this.getOpinionvaluebyid(kp, indexRequest.getKey());
		List<DataBean> dataList = null;
		// 获取列表
		if (searchResponseEntity.getData() != null) {
			dataList = GsonUtil.jsonToList(searchResponseEntity.getData().toString(), new TypeToken<List<DataBean>>(){}.getType());
			/*
			 * for (DataBean bean : dataList) { bean.setContent(""); }
			 */
		}
		return dataList;
	}
}
